package com.athl.gulimall.product.service.impl;

import com.athl.common.constant.ProductConstant;
import com.athl.common.utils.PageUtils;
import com.athl.common.utils.Query;
import com.athl.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.athl.gulimall.product.dao.AttrDao;
import com.athl.gulimall.product.dao.AttrGroupDao;
import com.athl.gulimall.product.dao.CategoryDao;
import com.athl.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.athl.gulimall.product.entity.AttrEntity;
import com.athl.gulimall.product.entity.AttrGroupEntity;
import com.athl.gulimall.product.entity.CategoryEntity;
import com.athl.gulimall.product.entity.vo.AttrGroupAndAttrVo;
import com.athl.gulimall.product.entity.vo.AttrGroupRelationVo;
import com.athl.gulimall.product.service.AttrGroupService;
import com.athl.gulimall.product.service.AttrService;
import com.athl.gulimall.product.vo.AttrGroupWithAttrsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private AttrDao attrDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 根据条件和catelogId分页查询分组信息
     *
     * @param params
     * @param catelogId
     * @return
     */
    @Override
    public PageUtils queryPageByCid(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_group_id", key).or().like("attr_group_name", key);
            });
        }
        if (catelogId == 0) {
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params),
                    wrapper);
            return new PageUtils(page);
        } else {
            wrapper.eq("catelog_id", catelogId);
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params),
                    wrapper);
            return new PageUtils(page);
        }


//        //如果三级分类的id = 0 就查询所有
//        if(catelogId == 0){
//            //分页条件 Query
//            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params),
//                            new QueryWrapper<AttrGroupEntity>());
//            return new PageUtils(page);
//        }else{
//            String key = (String) params.get("key");
//            //select * from pms_attr_group where catelog_id =?  and  (attr_group_id = key or attr_group_name like %key%)
//            //查询条件用QueryWrapper
//            QueryWrapper<AttrGroupEntity> warpper = new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId);
//            if(StringUtils.isEmpty(key)){
//                warpper.and((obj)->{
//                    obj.eq("att_group_id", key).or().like("attr_group_name", key);
//                });
//            }
//            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params),
//                    warpper);
//            return new PageUtils(page);
//        }

    }

    /**
     * 根据分组id attrGroupId 查询所有基本属性（规格参数） attr
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getAttrByAttrGroupId(Long attrgroupId) {
        //根据分组id查出关系标集合
        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId));
        //收集Long类型的attrId
        List<Long> attrIdList = relationEntityList.stream().map((attrAttrgroupRelationEntity) -> {
            Long attrId = attrAttrgroupRelationEntity.getAttrId();
            return attrId;
        }).collect(Collectors.toList());

        List<AttrEntity> attrEntities = null;
        //当着个list不为0
        if (attrIdList != null && attrIdList.size() > 0) {
            //根据id找到attr实体（属性信息）
            attrEntities = attrDao.selectBatchIds(attrIdList);
        }
        return attrEntities;
    }

    /**
     * 根据attrId和attrGroupId删除关联
     *
     * @param attrGroupRelationVo
     */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] attrGroupRelationVo) {
        List<AttrAttrgroupRelationEntity> entityList = Arrays.stream(attrGroupRelationVo).map((item) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBathRelations(entityList);
    }

    /**
     * 获取当前分组未关联的属性
     *
     * @param attrgroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils getNoRelation(Long attrgroupId, Map<String, Object> params) {
        //1. 当前分组（基本信息）只能关联自己所属的分类（手机）里面的所有属性（入网型号，上市年份）
        //2. 当前分组只能关联别的分组（主体）没有引用的属性（颜色）
        //2.1) 当前分类下的其他分组
        //2.2) 查出这些分组关联的属性
        //2.3) 从当前分类的所有属性中移除这些属性


        // 只能是当前分类
        //根据分组id查出分组属性
        AttrGroupEntity attrGroupEntity = baseMapper.selectById(attrgroupId);
        CategoryEntity categoryEntity = null;
        PageUtils pageUtils = null;
        if (attrGroupEntity != null) {
            categoryEntity = categoryDao.selectById(attrGroupEntity.getCatelogId());
            // 2.1) 没有被其他引用(查询当前分类下的其他分组)  商品id相同但是分组id不同
            List<AttrGroupEntity> groupEntityList = baseMapper.selectList(new QueryWrapper<AttrGroupEntity>()
                    .eq("catelog_id", attrGroupEntity.getCatelogId())
                   );
            //把这些其他分组的封装成list
            List<Long> groupIdList = groupEntityList.stream().map((item) -> {
                return item.getAttrGroupId();
            }).collect(Collectors.toList());

            QueryWrapper<AttrAttrgroupRelationEntity> wrapper1 = new QueryWrapper<>();

            if (groupIdList != null && groupEntityList.size() > 0) {
                //in查询 必须是List
                wrapper1.in("attr_group_id", groupIdList);
            }

            // 查询这些分组关联的属性
            List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(wrapper1);
            //属性id集合
            List<Long> attrIdList = relationEntityList.stream().map((item) -> {
                return item.getAttrId();
            }).collect(Collectors.toList());
            // 获取未被关联的属性的条件
            QueryWrapper<AttrEntity> wrapper2 = new QueryWrapper<AttrEntity>()
                    .eq("catelog_id", attrGroupEntity.getCatelogId())
                    .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
            //并把上面找到的其他分组 的组id排除
            if (attrIdList != null && attrIdList.size() > 0) {
                wrapper2.notIn("attr_id", attrIdList);
            }
            //模糊查询
            String key = (String) params.get("key");
            if (!StringUtils.isEmpty(key)) {
                wrapper2.and((w) -> {
                    w.eq("attr_id", key).or().like("attr_name", key);
                });
            }
            //IPage对象
            IPage<AttrEntity> page = attrService.page(new Query<AttrEntity>().getPage(params), wrapper2);
            pageUtils = new PageUtils(page);
        }
        return pageUtils;
    }

    /**
     * 根据分类id 查出所有分组以及这些分组下的属性
     * @param catelogId
     * @return
     */


    @Override
    public List<AttrGroupAndAttrVo> getGroupAndAttrByCateId(Long catelogId) {
        //1. 查询分组信息
        List<AttrGroupEntity> groupEntityList = baseMapper.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //2. 查出所有属性
        //把 grouplist分解成group
        List<AttrGroupAndAttrVo> attrVoList = new ArrayList<>(100);
        for (int i = 0; i < groupEntityList.size(); i++) {
            AttrGroupEntity attrGroupEntity = groupEntityList.get(i);
            List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_group_id", attrGroupEntity.getAttrGroupId()));
            List<Long> attrIds = attrAttrgroupRelationEntityList.stream().map(item -> {
                return item.getAttrId();
            }).collect(Collectors.toList());
            List<AttrEntity> attrEntities = null;
            if (attrIds != null && attrIds.size() > 0) {
                attrEntities = attrDao.selectBatchIds(attrIds);
            }
            AttrGroupAndAttrVo attrGroupAndAttrVo = new AttrGroupAndAttrVo();
            BeanUtils.copyProperties(attrGroupEntity, attrGroupAndAttrVo);
            attrGroupAndAttrVo.setAttrs(attrEntities);
            attrVoList.add(attrGroupAndAttrVo);
        }
        return attrVoList;
    }

}